var controller = require('../core/controller.js');
var cronJob = require('cron').CronJob;
var fs = require('fs'); // file system


var configurationFile = 'modules/morning/conf.json';
var job = null;


function onAlarm()
{
	controller.process_sensor(666, null);
	console.log('Alarm triggered.');
}

function setAlarmTime(hours, minutes)
{
	if(job != null)
		job.stop();

	job = new cronJob(
		'00 '+minutes+' '+hours+' * * *', // Runs every day
		onAlarm,
	 	null, 
	  	true /* Start the job right now */
	);

	console.log('Set the alarm to '+hours+':'+minutes);
}

function readFileAndSetAlarm()
{
	fs.readFile(configurationFile, function(err, data)
	{
		if(err)
			console.log('Could not read configuration file from alarmclock.js');
		else
		{
			var conf = JSON.parse(data);
			if(conf['gcalendar_min'] != undefined && conf['gcalendar_hour'] != undefined)
			{
				setAlarmTime(conf['gcalendar_hour'], conf['gcalendar_min']);
			}
			else
				console.log('Could not read gcalendar hours and minutes from conf.json');
		}
	});
}


function startListen() {

	readFileAndSetAlarm();

	fs.watchFile(configurationFile, readFileAndSetAlarm);

	console.log('Init alarm.');
}

module.exports.startListen = startListen;
